package com.nakaikensuke.SNE;

import java.io.UnsupportedEncodingException;

import com.nakaikensuke.tools.Cp437;

import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;

public class DirEntry implements Parcelable {
	private String _shortName = null;
	private String _longName = null;
	private boolean _isDir = false;
	private Drawable _icon = null;
	
	public DirEntry(
				String shortName,
				String longName) {
		_shortName = shortName;
		_longName = longName;
	}
	
	public DirEntry(
				byte[] shortName,
				byte[] longName,
				boolean isDir,
				String charset) {
		try {
			_isDir = isDir;
			
			///	UTF-8 ⇒ UNICODE変換
			_longName = new String(longName, "UTF8");
			
			///	UTF-8 ⇒ UNICODE ⇒ CP437変換
			byte[] unicode = new String(shortName, "UTF8").getBytes("UTF-16BE");
			byte[] cp437 = uni2cp437(unicode);

			///	ユーザ指定の文字コードに変換
			_shortName = new String(cp437, charset);
			
			_isDir = isDir;
			
		} catch (UnsupportedEncodingException e) {
			if(_longName == null) _longName = "";
			if(_shortName == null) _shortName = "";
		}
	}
	
	private byte[] uni2cp437(byte[] source) {
		byte[] dest = new byte[source.length / 2];
		
		for(int i = 0, j = 0; i < source.length; i += 2) {
			dest[j ++] = Cp437.lookup(source[i], source[i + 1]);
		}
		
		return dest;
	}
	
	public String getShortName() {
		return _shortName;
	}
	
	public String getLongName() {
		return _longName;
	}
	
	public boolean isDir() {
		return _isDir;
	}
	
	public void setIcon(Drawable icon) {
		_icon = icon;
	}
	
	public Drawable getIcon() {
		return _icon;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(_shortName);
		dest.writeString(_longName);
	}
	
	public static final Parcelable.Creator<DirEntry> CREATOR =
	new Creator<DirEntry>() {
		@Override
		public DirEntry[] newArray(int size) {
			return new DirEntry[size];
		}
		
		@Override
		public DirEntry createFromParcel(Parcel source) {
			String shortName = source.readString();
			String longName = source.readString();

			return new DirEntry(shortName, longName);
		}
	};
}
